package com.yangjie.autotest.util;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.yangjie.autotest.testcase.xml.Param;
import com.yangjie.autotest.testcase.xml.Params;
import com.yangjie.autotest.testcase.xml.Variable;
import com.yangjie.autotest.testcase.xml.Variables;

public class TestCaseUtils {

	private static Logger logger = Logger.getLogger("TestCaseUtils");	
	
	public static String getVarValue(String varName, Variables vars) {
		for (Variable var : vars.getVariable()) {
			if (var.getName().equalsIgnoreCase(varName)) {
				return var.getValue();
			}
		}
		return null;
	}
	
	public static String fillVariable(String arg, Variables vars) {
		Pattern p = Pattern.compile("\\$\\{\\w+}");
		Matcher m = p.matcher(arg);
		String tmp = arg;
		while (m.find()) {
			String group = m.group();
			String varName = group.replaceFirst("\\$\\{", "").replace("}", "");
			String value = getVarValue(varName, vars);
			group = group.replace("$", "\\$");
			group = group.replace("{", "\\{");
			logger.debug("fillVariable group=" + group + ";value=" + value);
			tmp = tmp.replaceAll(group, value);
		}
		return tmp;
	}

	public static String[] fillVariables(String[] args, Variables vars) {
		for (int i = 0; i < args.length; i++) {
			String tmp = fillVariable(args[i], vars);
			args[i] = tmp;
		}
		return args;
	}
	
	public static void fillVariables(Params params, Variables vars) {
		for (Param param:params.getParam()) {
			String tmp = fillVariable(param.getValue(), vars);
			param.setValue(tmp);
		}

	}
	
	public static String getParamValue(Params params, String name) {
		for(Param param: params.getParam()) {
			if(param.getName().equalsIgnoreCase(name)) {
				return param.getValue();
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println("a".replaceAll("a", "\\\\test"));
	}
}
